<script setup>

import { computed, onMounted, ref } from 'vue';
import { IconStarFill } from '../icon/index.js'

// 组件通过设置 font-size 样式,调整大小
// 组件事件 change-count 星数被改变时的回调, 组件暴露 getCount函数, starCount数据.
// <StarBox style="font-size:0.6rem;" :count="3" :checked="true" @change-count="事件函数" />
// 同星数点第二次表示取消, 星数置为0

const props = defineProps({
    total: { //总星数
        type: Number,
        default: 5
    },
    count: { //实星数
        type: Number,
        default: 0
    },
    checked: { //能否改变实星数
        type: Boolean,
        default: false
    },
});
const emits = defineEmits(['changeCount']);
const starCount = ref(0);

const starIconStyleObj = computed(()=>{
    let style = {};
    if(props.checked) {//星可选
        style.cursor = 'pointer';
    }
    return style;
});
//改变 star count
function doChangeStarCount(count) {
    if(props.checked) {//星可选
        if(count == starCount.value) {
            //同星数点第2次表示取消, 星数置为0
            count = 0;
        }
        starCount.value = count;
        emits('changeCount', count);
    }
}

defineExpose({
    //返回当前星数
    getCount: () => starCount.value,
    starCount: starCount
});

onMounted(()=>{
    starCount.value = props.count;
});

</script>
<template>
    <div class="star-box-dl">
        <div class="star-line-dl" >
            <IconStarFill class="star-icon-dl" v-for="(t) in props.total" :key="t"
            :style="starIconStyleObj" @click="doChangeStarCount(t)" />
        </div>
        <div class="star-fill-dl"  >
            <IconStarFill class="star-icon-dl" v-for="(c) in starCount" :key="c"
            :style="starIconStyleObj" @click="doChangeStarCount(c)" />
        </div>
    </div>
</template>
<style scoped>
.star-box-dl {
    position: relative;
    height: 1em;
}
.star-line-dl {
    display: flex;
}
.star-fill-dl {
    display: flex;
    position: absolute;
    top: 0;
    left: 0;
    z-index: 1;
}

.star-icon-dl {
    display: block;
}
.star-line-dl .star-icon-dl {
    color: #ccc;
    width: 1em;
    height: 1em;
}
.star-fill-dl .star-icon-dl {
    color: #F7DD4E;
    width: 1em;
    height: 1em;
}
</style>